import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class XMLDecoder {
	public static List<WidgetIdMapping> getMappingFromFile(String fileName) {
		Document document = getDocument(fileName);
		
		List<WidgetIdMapping> mappings = new ArrayList<WidgetIdMapping>();
		
		Element rootElement =  document.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> elements = rootElement.elements();
//		System.out.println("长度" + elements.size());
		mappings = getNeededElement(rootElement);
		return mappings;
	}
	
	public static List<WidgetIdMapping> getNeededElement(Element root) {
		List<Element> elements = root.elements();
		List<WidgetIdMapping> widgetIdMappings = new ArrayList<WidgetIdMapping>();
		if (elements == null || elements.size() == 0) {
			return widgetIdMappings;
		}
		for(Element element : elements) {
			widgetIdMappings.addAll(getNeededElement(element));
			String s = element.attributeValue("id");
			if(s ==null)
				continue;
			String typeName = element.getName();
			System.out.println(typeName);
			String param = getParamName(s);
			System.out.println(param);
			String id = "R.id." + s.substring(5);
			System.out.println(id + "\n----------------------------------");
			WidgetIdMapping mapping = new WidgetIdMapping();
			mapping.setType(typeName);
			mapping.setParam(param);
			mapping.setId(id);
			widgetIdMappings.add(mapping);
		}
		return widgetIdMappings;
	}
	
	public static String getParamName(String s) {
		String newString = s.substring(5);
		String[] strings = newString.split("_");
		
		StringBuilder sb = new StringBuilder();
		
		sb.append(strings[0]);
		for(int i = 1; i < strings.length; i ++) {
			String low = strings[i].substring(0, 1);
			String noChange = strings[i].substring(1, strings[i].length());
			low = low.toUpperCase();
			sb.append(low + noChange);
		}
//		System.out.println(sb.toString());
		return sb.toString();
	}
	
	public static Document getDocument(String fileName) {
		Document document = null;
		SAXReader reader = new SAXReader();
		try {
			document = reader.read(new File(fileName));
		} catch (DocumentException e) {
			e.printStackTrace();
			return null;
		}
		return document;
	}
}
